<template>
    <div class="search-container" >
        <!-- 搜索输入区域 -->
        <div class="search-header">
            <el-radio-group v-model="searchType" @change="handleSearch">
                <el-radio-button label="article">文章</el-radio-button>
                <el-radio-button label="library">知识库</el-radio-button>
                <el-radio-button label="user">用户</el-radio-button>
            </el-radio-group>

            <div class="search-input-group">
                <el-input v-model="keywords" placeholder="请输入搜索关键词" clearable @keyup.enter="handleSearch"
                    class="search-input">
                    <template #prefix>
                        <el-icon>
                            <search />
                        </el-icon>
                    </template>
                </el-input>
                <el-button type="primary" @click="handleSearch" class="search-button">
                    搜索
                </el-button>
            </div>
        </div>

        <!-- 搜索结果展示 -->
        <div class="search-results">
            <template v-if="loading">
                <el-skeleton :rows="6" animated />
            </template>

            <template v-else>
                <el-empty v-if="results.length === 0" description="暂无搜索结果" />

                <!-- 文章结果 -->
                <template v-if="searchType === 'article'">
                    <div class="result-grid">
                        <article-card v-for="item in results" :key="item.articleId" :article="item"
                            @click="handleArticleClick(item)" class="result-card" />
                    </div>
                </template>

                <!-- 知识库结果 -->
                <template v-if="searchType === 'library'">
                    <div class="result-grid">
                        <library-card v-for="item in results" :key="item.libraryId" :library="item"
                            @click="handleLibraryClick(item)" class="result-card" />
                    </div>
                </template>

                <!-- 用户结果 -->
                <template v-if="searchType === 'user'">
                    <div class="user-list">
                        <user-card v-for="user in results" :key="user.userId" :user="{
                userId: user.userId,
                nickName: user.nickName,
                avatar: user.avatar,
                libraryCount: user.libraryCount || 0  // 新增知识库数量字段
              }" @click="handleUserClick(user)" class="search-user-card" />
                    </div>
                </template>

                <!-- 分页按钮 -->
                <div class="pagination">
                    <el-button @click="handlePrevPage" :disabled="currentPage === 1">上一页</el-button>
                    <el-button @click="handleNextPage" :disabled="results.length < pageSize">下一页</el-button>
                </div>


            </template>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import { Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import require from '../require'
import ArticleCard from './ArticleCard.vue'
import LibraryCard from './LibraryCard.vue'
import UserCard from './UserCard.vue'
// 搜索相关状态
const searchType = ref('article')
const keywords = ref('我')
const loading = ref(false)
const results = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

const router = useRouter()

// 分页处理
const handlePageChange = (page) => {
    currentPage.value = page
    handleSearch()
}

const handlePrevPage = () => {
    if (currentPage.value > 1) {
        currentPage.value--;
        handleSearch().then(() => {
            // 等待页面渲染完成后，滚动到顶部
            Vue.nextTick(() => {
                window.scrollTo(0, 0);
            });
        });
    }
};

// 处理下一页点击事件
const handleNextPage = () => {
    const l = results.value.length;
    if (l === pageSize.value) {
        currentPage.value++;
        handleSearch().then(() => {
            // 等待页面渲染完成后，滚动到顶部
            Vue.nextTick(() => {
                window.scrollTo(0, 0);
            });
        });
    }
};



// 执行搜索
const handleSearch = async () => {
    if (!keywords.value.trim()) return
    
    loading.value = true
    try {
        // 根据搜索类型选择接口地址
        const apiMap = {
            article: 'searchArticle',
            library: 'searchLibrary',
            user: 'searchUser'
        }

        if (searchType.value === 'user') {
            results.value = await queryUser((currentPage.value - 1) * pageSize.value, pageSize.value, keywords.value);

        } else if (searchType.value === 'article') {
            results.value = await queryCollectedArticle((currentPage.value - 1) * pageSize.value, pageSize.value, keywords.value);
        } else if (searchType.value === 'library') {
            results.value = await queryCollectedLibrary((currentPage.value - 1) * pageSize.value, pageSize.value, keywords.value);
        }

    } catch (error) {
        console.error('搜索失败:', error)
    } finally {
        loading.value = false
    }
}

const queryCollectedArticle = async (start, size, keywords) => {
    const res = await require.post('user/searchArticle', {
        start: start,
        size: size,
        keyword: keywords,
    });
    const alist = [];
    for (let i = 0; i < res.articleAmount; i++) {
        const e = res.articleList[i];
        alist.push({
            articleId: e.articleId,
            title: e.title,
            author: e.author.nickName,
            updateTime: e.updateTime,
            likedAmounts: e.likedAmounts,
            collectedAmounts: e.collectedAmounts,
            commentedAmounts: e.commentedAmounts,
            currentUserCollect: e.currentUserCollect,
            currentUserLike: e.currentUserLike,
            creatorName: e.author.nickName,
            creatorId: e.author.userId,
        })
    }
    return alist
}

const queryCollectedLibrary = async (start, size,keywords) => {
    const res = await require.post('user/searchLibrary', {
        start: start,
        size: size,
        keyword: keywords,
    });
    const alist = [];
    for (let i = 0; i < res.libraryAmount; i++) {
        const e = res.libraryList[i];
        alist.push({
            libraryId: e.libraryId,
            name: e.libraryName,
            description: e.description,
            articleCount: e.articleAmounts,
            createTime: e.createTime,
            updateTime: e.updateTime,
            creatorId: e.creatorUser.userId,
            isPublic: e.isPublic,
            likedAmounts: e.likedAmounts,
            collectedAmounts: e.collectedAmounts,
            commentedAmounts: e.commentedAmounts,
            currentUserCollect: e.currentUserCollect,
            currentUserLike: e.currentUserLike,
            creatorName: e.creatorUser.nickName,
            creatorId: e.creatorUser.userId,
        })
    }
    return alist
}

const queryUser = async (start, size, keywords) => {
    const res = await require.post('user/searchUser', {
        start: start,
        size: size,
        keyword: keywords,
    });
    const ulist = [];
    for (let i = 0; i < res.userAmount; i++) {
        const e = res.userList[i];
        ulist.push({
            userId: e.userId,
            nickName: e.nickName,
            avatar: e.avatarUrl,
            libraryCount: e.libraryAmount || 0  // 新增知识库数量字段
        })
    }
    return ulist
}
    



// 点击事件处理
const handleArticleClick = (article) => {
  const r = router.resolve({
    name: 'HisArticle',
    query: { articleId: article.articleId }
  })
  window.open(r.href, '_blank')
}

const handleLibraryClick = (library) => {
    const r = router.resolve({
        name: 'HisLibrary',
        query: { id: library.libraryId }
    })
    window.open(r.href, '_blank')
}

const handleUserClick = (user) => {
    const r = router.resolve({
        name: 'UserProfile',
        query: { userId: user.userId }
    })
    window.open(r.href, '_blank')
}
</script>

<style scoped>
.search-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.search-header {
  text-align: center;
  margin-bottom: 30px;
}

.search-input-group {
  display: flex;
  gap: 10px;
  margin-top: 20px;
  max-width: 600px;
  margin: 20px auto;
}

.search-input {
  flex: 1;
}

.search-button {
  width: 100px;
}

.result-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.result-card:hover {
  transform: translateY(-5px);
  transition: transform 0.3s ease;
}

.user-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  padding: 15px;
}

.search-user-card {
  transition: all 0.3s ease;
  
  &:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.user-card {
  cursor: pointer;
  transition: box-shadow 0.3s;
}

.user-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-details h3 {
  margin: 0;
  color: #303133;
}

.bio {
  margin: 5px 0 0;
  color: #909399;
  font-size: 0.9em;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.el-radio-group {
  margin-bottom: 20px;
}
</style>
